package com.haredot.config;

import com.haredot.constraint.RabbitConst;
import com.haredot.dto.EmailDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.handler.annotation.Header;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Configuration
@EnableConfigurationProperties(MailProperties.class)
@Slf4j
public class EmailConfig {

    @Resource
    private MailProperties mailProperties;

    @Resource
    private JavaMailSender javaMailSender;

    @Bean("emailQueue")
    public Queue emailQueue() {
        return QueueBuilder
                .durable(RabbitConst.EMAIL_QUEUE)
                .build();
    }


    @RabbitListener(queues = RabbitConst.EMAIL_QUEUE)
    public void sendMail(Channel channel, EmailDTO emailDTO, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception {
        // 获取邮件，并发送
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

            helper.setFrom(mailProperties.getUsername(), "Haredot");
            helper.setTo(emailDTO.getTo());
            helper.setSubject(emailDTO.getSubject());
            helper.setText(emailDTO.getContent(), true);
            // 发送邮件
            javaMailSender.send(helper.getMimeMessage());

            channel.basicAck(deliveryTag, false);
            log.info("邮件已发送给{}....", emailDTO.getTo());
        } catch (Exception e) {
            log.warn("邮件发送失败，重新入队。失败的原因是" + e.getMessage());
            // 发送失败，重新投递，继续发送
            channel.basicNack(deliveryTag, false, true);
        }

    }
}
